package com.adgroup.smartnote;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import JsonModel.Category;
import JsonModel.Group;
import JsonModel.User;
import JsonModel.UserLogo;
import Net.JsonParse;
import Utilities.Configuration;
import adapter.AdapterCategories;
import adapter.AdapterCategories.Adapter;
import adapter.AdapterUserLogo;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import animationmenu.CollapseAnimation;
import animationmenu.ExpandAnimation;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.androidquery.AQuery;

import database.Database;

public class CreateGroup extends SherlockFragmentActivity{

	private ActionBar mActionBar;
	private DisplayMetrics metrics;
	private int panelWidth;
	private LinearLayout menuPanelLogo;
	private LinearLayout menuPanelCategory;
	private LinearLayout slidingPanel;
	private ListView lvLogo;
	private ProgressBar progressLogo;
	private ListView lvCat;
	private ProgressBar progressCat;
	private Button btnCat, btnLogo, btnRegister;
	private TextView tvCat, tvCalenderExpried;
	private CheckBox chkYes, chkNo;
	private ImageView ivLogo;
	private ImageButton btnCalenderExpried;
	private EditText et;
	private Adapter adapCat;
	private adapter.AdapterUserLogo.Adapter adapLogo;
	private boolean isExpandedCat;
	private boolean isExpandedLogo;

	ArrayList<UserLogo> logos = new ArrayList<UserLogo>();
	ArrayList<Category> cats = new ArrayList<Category>();
	private int mYear;
	private int mMonth;
	private int mDay;
	boolean isPublish = true;
	User u;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menusearchfriend, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuLoginSearchFriend:
			
			break;
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.creategroup);
		
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.buttonlogin));
		
		//config menu slide
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		panelWidth = (int) ((metrics.widthPixels) * 0.75);

		//slide menu logo
		menuPanelLogo = (LinearLayout) findViewById(R.id.menuPanelGroupCreateGroup);
		android.widget.FrameLayout.LayoutParams menuPanelParameters = (FrameLayout.LayoutParams) menuPanelLogo
				.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanelLogo.setLayoutParams(menuPanelParameters);
		
		//slide menu category
		menuPanelCategory = (LinearLayout) findViewById(R.id.menuPanelCatCreateGroup);
		android.widget.FrameLayout.LayoutParams menuPanelParametersCat = (FrameLayout.LayoutParams) menuPanelCategory
				.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanelCategory.setLayoutParams(menuPanelParametersCat);
		
		//main content
		slidingPanel = (LinearLayout) findViewById(R.id.slidingmenuCreateGroup);
		android.widget.FrameLayout.LayoutParams slidingPanelParametersMain = (FrameLayout.LayoutParams) slidingPanel
				.getLayoutParams();
		slidingPanelParametersMain.width = metrics.widthPixels;
		slidingPanel.setLayoutParams(slidingPanelParametersMain);
		
		//mapping
		btnCat = (Button) findViewById(R.id.buttonCatCreateGroup);
		btnLogo = (Button) findViewById(R.id.buttonLogoCreateGroup);
		btnRegister = (Button) findViewById(R.id.buttoncreategroup);
		et = (EditText) findViewById(R.id.editTextTitleCreateGroup);
		lvCat = (ListView) findViewById(R.id.listViewCatCreateGroup);
		lvLogo = (ListView) findViewById(R.id.listViewGroupCreateGroup);
		progressCat = (ProgressBar) findViewById(R.id.progressBarwaitingCatCreateGroup);
		progressLogo = (ProgressBar) findViewById(R.id.progressBarwaitingGroupCreateGroup);
		tvCat = (TextView) findViewById(R.id.textViewCatCreateGroup);
		ivLogo = (ImageView) findViewById(R.id.imageViewLogoCreateGroup);
		chkNo = (CheckBox) findViewById(R.id.checknoCreateGroup);
		chkYes = (CheckBox) findViewById(R.id.checkyesCreateGroup);
		btnCalenderExpried = (ImageButton) findViewById(R.id.imageButtonDateExpriedCreateGroup);
		tvCalenderExpried = (TextView) findViewById(R.id.textViewDateExpriedCreateGroup);
		
		//load categories
		new AsyncLoadCategory().execute();
		//load logo
		new AsynLoadLogo().execute();
		
		//click item list view category
		lvCat.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				tvCat.setText(cats.get(arg2).getName());
				tvCat.setTag(cats.get(arg2).getId());
				isExpandedCat = false;

				// Collapse
				new CollapseAnimation(slidingPanel, panelWidth,
						TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
						TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
						0, 0.0f);
			}
		});
		//click item list view logo
		lvLogo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				AQuery aq = new AQuery(arg1);
				Bitmap placeholder = aq.getCachedImage(R.drawable.imageload);
				aq.id(ivLogo).image(logos.get(arg2).getLink(), true,
							true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK, 1.0f);
				ivLogo.setTag(logos.get(arg2).getLogoid());
				isExpandedLogo = false;

				// Collapse
				new CollapseAnimation(slidingPanel, panelWidth,
						TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
						TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
						0, 0.0f);
			}
		});
		
		//check
		chkYes.setChecked(true);
		chkNo.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkYes.setChecked(false);
				}
				else{
					chkYes.setChecked(true);
				}
			}
		});
		chkYes.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkNo.setChecked(false);
				}
				else{
					chkNo.setChecked(true);
				}
			}
		});
		//choose categories
		btnCat.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuPanelCategory.setVisibility(View.VISIBLE);
				menuPanelLogo.setVisibility(View.GONE);
				if (!isExpandedCat) {
					isExpandedCat = true;
					
					// Expand
					new ExpandAnimation(slidingPanel, panelWidth,
							Animation.RELATIVE_TO_SELF, 0.0f,
							Animation.RELATIVE_TO_SELF, 0.75f, 0, 0.0f, 0, 0.0f);
				} else {
					isExpandedCat = false;

					// Collapse
					new CollapseAnimation(slidingPanel, panelWidth,
							TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
							TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
							0, 0.0f);

				}
			}
		});
		btnLogo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				menuPanelCategory.setVisibility(View.GONE);
				menuPanelLogo.setVisibility(View.VISIBLE);
				if (!isExpandedLogo) {
					isExpandedLogo = true;

					// Expand
					new ExpandAnimation(slidingPanel, panelWidth,
							Animation.RELATIVE_TO_SELF, 0.0f,
							Animation.RELATIVE_TO_SELF, 0.75f, 0, 0.0f, 0, 0.0f);
				} else {
					isExpandedLogo = false;

					// Collapse
					new CollapseAnimation(slidingPanel, panelWidth,
							TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
							TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
							0, 0.0f);

				}
			}
		});
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String title = et.getText().toString();
				u = new Database(CreateGroup.this).getUser();
				
				if(title.equalsIgnoreCase("")){
					new AlertDialog.Builder(CreateGroup.this)
					.setTitle(getResources().getString(R.string.titlealerterrorcreategroup))
					.setMessage(getResources().getString(R.string.messagealertcreategrouperrortitle))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
				}
				else if(u==null){
					new AlertDialog.Builder(CreateGroup.this)
					.setTitle(getResources().getString(R.string.buttonlogin))
					.setMessage(getResources().getString(R.string.messagealertcreategrouplogin))
					.setNegativeButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent i = new Intent(CreateGroup.this, LoginActivity.class);
							startActivityForResult(i, Configuration.requestCreateGroupToLogin);
						}
					})
					.setPositiveButton(CreateGroup.this.getResources().getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
					
				}
				else{					
					new AsynCreateGroup().execute();
					
				}
			}
		});
		
		//calender
		Calendar c = Calendar.getInstance();
		mYear = c.getTime().getYear()+1900+1;
		mMonth = c.getTime().getMonth();
		mDay = c.getTime().getDate();
		updateBirthday();
		btnCalenderExpried.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				DatePickerDialog DPD = new DatePickerDialog(CreateGroup.this,dateSetListener, mYear, mMonth, mDay);
				DPD.show();	
				updateBirthday();
			}
		});
	}
	//asynctask create group
	class AsynCreateGroup extends AsyncTask<Void, Void, String>
	{
		
		private ProgressDialog progress;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(CreateGroup.this, "",
					getResources().getString(R.string.progresscreategroup), true);
		}
		@Override
		protected String doInBackground(Void... arg0) {
			int isPublish = 1;
			if(chkYes.isChecked()){
				isPublish = 1;
			}
			else{
				isPublish = 0;
			}
			return new JsonParse().createGroup(CreateGroup.this, u.getUserId(),mYear+"-"+mMonth+"-"+mDay,tvCat.getTag().toString(),ivLogo.getTag().toString(),et.getText().toString(),isPublish);
		}
		@Override
		protected void onPostExecute(String result) {
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(!r.equalsIgnoreCase("0")){
					JSONObject obj = json.getJSONArray(Configuration.result).getJSONObject(0);
					
					 String groupId = obj.getString(Group.keyGroupId);
					 String groupCatName = obj.getString(Group.keyGroupCatName);
					 String link = obj.getString(Group.keylink);
					 String groupCatId = obj.getString(Group.keyGroupCatId);
					 String title = obj.getString(Group.keyTitle);
					 String logoId = obj.getString(Group.keyLogoId);
					 String monitor = obj.getString(Group.keyMonitor);
					 String time = obj.getString(Group.keyTime);
					 String isPublish = obj.getString(Group.keyIsPublish);
					 String expried = obj.getString(Group.keyExpired);
					 String total = "1";
					Group g = new Group(groupId, groupCatId, groupCatName, logoId, time, expried, isPublish, monitor, title, link, total);
					new Database(CreateGroup.this).resetGroup();
					new Database(CreateGroup.this).setGroup(g);
					new AlertDialog.Builder(CreateGroup.this)
					.setTitle(getResources().getString(R.string.titlealertcreategroup))
					.setMessage(getResources().getString(R.string.messagealertcreategroupsuccess))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
									Intent i = new Intent(CreateGroup.this, AddMemberToGroupActivity.class);
									startActivity(i);
								}
					}).show();
				}
				else{
					new AlertDialog.Builder(CreateGroup.this)
					.setTitle(getResources().getString(R.string.titlealertcreategroup))
					.setMessage(getResources().getString(R.string.messagealertcreategroupfail))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
					}).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			progress.dismiss();
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, arg2);
		if(requestCode==Configuration.requestCreateGroupToLogin && resultCode==RESULT_OK){//register then login
			u = new Database(CreateGroup.this).getUser();
			if(u!=null){
				new AsynCreateGroup().execute();
			}
		
		}

	}
	protected void updateBirthday() {
		tvCalenderExpried.setText(new StringBuilder()
				.append(mDay).append("-").append(mMonth + 1).append("-")
				.append(mYear));
	}
	private OnDateSetListener dateSetListener = new OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
			mYear = arg1;
			mMonth = arg2;
			mDay = arg3;
			updateBirthday();
		}
	};
	
	//load logo group
	class AsynLoadLogo extends AsyncTask<Void, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressLogo.setVisibility(View.VISIBLE);
		}
		@Override
		protected String doInBackground(Void... params) {			
			return new JsonParse().getUserLogo(CreateGroup.this);			
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			try {
				JSONObject json = new JSONObject(result);
				JSONArray results = json.getJSONArray("result");
				for(int i=0;i<results.length();i++){
					JSONObject obj = results.getJSONObject(i);
					String gender = obj.getString(UserLogo.keyGender);
					String link = obj.getString(UserLogo.keyLink);
					int logoid = Integer.parseInt(obj.getString(UserLogo.keyLogoId));
					logos.add(new UserLogo(gender,link,logoid));
				}
				adapLogo = new AdapterUserLogo().new Adapter(CreateGroup.this, logos, 1);
				lvLogo.setAdapter(adapLogo);
				progressLogo.setVisibility(View.GONE);
				lvLogo.setVisibility(View.VISIBLE);
				 Log.d("log","finished");
			} catch (JSONException e) {
				Log.d("error",e.getMessage());
				e.printStackTrace();
			}
			
		}
	}
	
	//asyntask load category
	class AsyncLoadCategory extends AsyncTask<Void, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressCat.setVisibility(View.VISIBLE);
		}
		@Override
		protected String doInBackground(Void... params) {
			return new JsonParse().loadCategories();
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject json = new JSONObject(result);
				if(!json.getString(Configuration.result).equalsIgnoreCase(Configuration.norow)){
					JSONArray arr = json.getJSONArray(Configuration.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String name = obj.getString(Category.KEY_GroupCatName);
						String id = obj.getString(Category.KEY_GroupCatId);
						Category cat = new Category(name, id);
						cats.add(cat);
					}
					adapCat = new AdapterCategories(CreateGroup.this, cats).new Adapter();
					lvCat.setAdapter(adapCat);
					progressCat.setVisibility(View.GONE);
					lvCat.setVisibility(View.VISIBLE); 
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			
		}
	}
}
